﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EnvDTE;
using System.Diagnostics;
using HiUpdateTools.Core;
using System.IO;
using EnterpriseDT.Net.Ftp;
using Ionic.Zip;
using System.Threading;
using AndrysNet.HiUpdateTools_Addin;



namespace HiUpdateTools
{
    [System.Runtime.InteropServices.GuidAttribute("5D92A891-23AB-4550-9BD8-72DA499FF39B")]
    public partial class DeployForm : Form
    {

        public DeployForm()
        {
            InitializeComponent();
            pictureBox1.Image = AndrysNet.HiUpdateTools_Addin.Resources.ic_update_metro;
            pictureBox2.Image = AndrysNet.HiUpdateTools_Addin.Resources.animatedCircle;
            pictureBox2.Visible = false;
            ///       label10.Image = AndrysNet.HiUpdateTools_Addin.Resources.WizardLabelImg;



        }
        public DTE DTE { get; set; }
        private Version NewVersion;
        ServerConfig serverConfig;
        private void SaveConfig()
        {
            //Save server config
            txApplicationName.Focus();

            Window window = confFile.Open();
            TextDocument txt = (TextDocument)window.Document.Object("TextDocument");
            conf.ApplicationName = txApplicationName.Text;
            conf.Version = txVersion.Text;
            conf.DeployType = (ApplicationType)cbApplicationType.SelectedValue;
            conf.ServerPathType = (PathType)cbServerPathType.SelectedValue;

            conf.ServerPath = txServerPath.Text;
            conf.ServerUserName = txServerUserName.Text;
            conf.ServerPassword = txServerPassword.Text;
            conf.ServerAnonymous = chServerAnonymous.Checked;

            txt.Selection.SelectAll();
            txt.Selection.Delete();
            txt.Selection.Insert(conf.ToXml());
            NewVersion = new Version(txVersion.Text);
            confFile.Save();

            //Save client config

            window = clientConfFile.Open();
            txt = (TextDocument)window.Document.Object("TextDocument");
            clientConfig.ClientPath = txClientPath.Text;
            clientConfig.PassiveMode = cbClientPassiveMode.Checked;
            clientConfig.ClientPathType = (PathType)cbClientPathType.SelectedValue;
            clientConfig.ClientUserName = txClientUserName.Text;
            clientConfig.ClientPassword = Convert.ToBase64String(Encoding.UTF8.GetBytes(txClientPassword.Text));
            clientConfig.ClientAnonymous = cbClientAnonymous.Checked;
            clientConfig.AutoUpdate = cbClientAutoUpdate.Checked;
            txt.Selection.SelectAll();
            txt.Selection.Delete();
            txt.Selection.Insert(clientConfig.ToXml());
            clientConfFile.Save();
        }
        private void WriteAssemblyInfo()
        {
            WriteLine("Writing assembly information to projects");
            conf.Projects.ForEach(item =>
                            {
                                if (item.WriteVerion)
                                {
                                    Project project = FindProject(item.Name);
                                    Property assemblyVersion = project.Properties.Item("AssemblyVersion");
                                    Property assemblyFileVersion = project.Properties.Item("AssemblyFileVersion");
                                    assemblyVersion.Value = txVersion.Text;
                                    assemblyFileVersion.Value = txVersion.Text;
                                    project.Save(null);
                                }
                            });
        }
        private void btDeploy_Click(object sender, EventArgs e)
        {
            try
            {
                btDeploy.Enabled = false;
                SaveConfig();
                WriteAssemblyInfo();
                WriteChangeLog();
                WriteLine("Run building projects ");
                SetStatus("Run building projects ", Color.Gray, DeployState.Run);
                Application.DoEvents();
                DTE.Solution.SolutionBuild.BuildProject("Release", CurrentProject.UniqueName, true);
                WriteLine("Run deploy application");
                SetStatus("Run deploy application...", Color.Gray, DeployState.Run);

                ThreadPool.QueueUserWorkItem(a =>
                {
                    try
                    {
                        switch (conf.ServerPathType)
                        {
                            case PathType.file:
                                {
                                    string destinatin = conf.ServerPath.TrimEnd("\\".ToCharArray()) + "\\" + conf.ApplicationName + "\\";
                                    if (!Directory.Exists(destinatin))
                                        Directory.CreateDirectory(destinatin);

                                    if (File.Exists(destinatin + "ServerConfig.xml"))
                                        serverConfig = ServerConfig.Load(destinatin + "ServerConfig.xml", typeof(ServerConfig)) as ServerConfig;
                                    else
                                        serverConfig = new ServerConfig();
                                    if (!string.IsNullOrEmpty(serverConfig.Version) && NewVersion.CompareTo(new Version(serverConfig.Version)) <= 0)
                                    {
                                        throw new Exception("On destination is exist newer version");

                                    }
                                    serverConfig.Version = NewVersion.ToString();
                                    serverConfig.Files = new List<ServerConfigFile>();
                                    serverConfig.Name = conf.ApplicationName;

                                    string versionPath = destinatin + NewVersion.ToString();
                                    Directory.CreateDirectory(versionPath);
                                    Copy(ProjectPath + "bin\\Release\\", versionPath);

                                    ///  File.Copy( + conf.ApplicationName + ".exe", versionPath+"\\" + conf.ApplicationName + ".exe");
                                    serverConfig.Save(destinatin + "ServerConfig.xml");
                                    break;
                                }

                            case PathType.ftp:
                                {
                                    string destinatin = conf.ServerPath.TrimEnd("/".ToCharArray()) + "/" + conf.ApplicationName + "/";
                                    string tempFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\HiUpdate\\" + conf.ApplicationName;
                                    Directory.CreateDirectory(tempFolder);
                                    FTPClient ftp = new FTPClient();
                                    ftp.RemoteHost = conf.ServerPath.Split("/".ToCharArray())[0];
                                    string remotePath = conf.ServerPath.Replace(ftp.RemoteHost, "");
                                    if (string.IsNullOrEmpty(remotePath))
                                        remotePath = "/";
                                    else
                                    {
                                        remotePath = remotePath.TrimEnd("/".ToCharArray()) + "/";

                                    }

                                    ftp.Connect();
                                    if (!conf.ServerAnonymous)
                                    {
                                        ftp.User(conf.ServerUserName);
                                        ftp.Password(conf.ServerPassword);
                                    }
                                    ftp.TransferType = FTPTransferType.BINARY;

                                    if (!ExistFolderOnFtp(ftp, remotePath + conf.ApplicationName + "/"))
                                    {

                                        ftp.MkDir(remotePath + conf.ApplicationName + "/");


                                    }

                                    if (ftp.Exists(remotePath + conf.ApplicationName + "/" + "ServerConfig.xml"))
                                    {
                                        File.WriteAllBytes(tempFolder + "\\ServerConfig.xml", ftp.Get(remotePath + conf.ApplicationName + "/" + "ServerConfig.xml"));
                                        serverConfig = ServerConfig.Load(tempFolder + "\\ServerConfig.xml", typeof(ServerConfig)) as ServerConfig;
                                    }
                                    else
                                        serverConfig = new ServerConfig();


                                    if (!string.IsNullOrEmpty(serverConfig.Version) && NewVersion.CompareTo(new Version(serverConfig.Version)) <= 0)
                                    {
                                        throw new Exception("On destination is exist newer version");

                                    }
                                    serverConfig.Version = NewVersion.ToString();
                                    serverConfig.Name = conf.ApplicationName;
                                    serverConfig.Files = new List<ServerConfigFile>();
                                    string versionPath = tempFolder + "\\" + NewVersion.ToString();
                                    Directory.CreateDirectory(versionPath);
                                    Copy(ProjectPath + "bin\\Release\\", versionPath);
                                    string remoteVersionPath = remotePath + conf.ApplicationName + "/" + NewVersion.ToString() + "/";

                                    if (!ExistFolderOnFtp(ftp, remoteVersionPath))
                                    {
                                        ftp.MkDir(remoteVersionPath);
                                    }
                                    CopyToFtp(ftp, versionPath, remoteVersionPath);



                                    // File.Copy(+conf.ApplicationName + ".exe", versionPath + "\\" + conf.ApplicationName + ".exe");
                                    serverConfig.Save(tempFolder + "\\ServerConfig.xml");
                                    ftp.Put(File.ReadAllBytes(tempFolder + "\\ServerConfig.xml"), remotePath + conf.ApplicationName + "/" + "ServerConfig.xml");

                                    break;
                                }

                            case PathType.http:
                                {
                                    throw new Exception("Http deployment is not yet supported.To deploy the Web server use FTP or filesystem.");
                                    //System.Net.WebClient wc = new System.Net.WebClient();
                                    //wc.UploadFile()
                                    break;
                                }
                            case PathType.https:
                                {
                                    throw new Exception("Https deployment is not yet supported.To deploy the Web server use FTP or filesystem.");
                                    //System.Net.WebClient wc = new System.Net.WebClient();
                                    //wc.UploadFile()
                                    break;
                                }
                            case PathType.ftps:
                                {
                                    throw new Exception("ftps deployment is not yet supported.To deploy the ftp server use FTP or filesystem.");
                                    //System.Net.WebClient wc = new System.Net.WebClient();
                                    //wc.UploadFile()
                                    break;
                                }
                        }

                        SetStatus("Deploy is successfully done", Color.Green, DeployState.Ok);
                    }
                    catch (Exception ex)
                    {

                        SetStatus("Error: " + ex.Message, Color.Red, DeployState.Error);

                        WriteLine("Error throw exception in Deploay '{0}' + {1}", ex.Message, ex.StackTrace);

                    }
                    finally
                    {

                        RunOnUiThread(() =>
                        {
                            btDeploy.Enabled = true;

                        });
                    }
                });


            }
            catch (Exception ex)
            {

                SetStatus("Error: " + ex.Message, Color.Red, DeployState.Error);

                WriteLine("Error throw exception in Deploay '{0}' + {1}", ex.Message, ex.StackTrace);

            }



        }

        private void WriteChangeLog()
        {
            Window window = _ChangeLogFile.Open();
            TextDocument txt = (TextDocument)window.Document.Object("TextDocument");
         
            StringBuilder sb= new StringBuilder();
            this.conf.ChangeLogs.OrderByDescending(item=>item.Date).ToList().ForEach(item=>{
                sb.AppendLine("------------------");
                sb.AppendLine(string.Format("Version:{0} Date:{1}",item.Version,item.Date));
                sb.AppendLine(item.Info);
            
            });
          
            txt.Selection.SelectAll();
            txt.Selection.Delete();
            txt.Selection.Insert(sb.ToString());
            _ChangeLogFile.Save();
        }

        public void RunOnUiThread(System.Action action)
        {

            if (this.InvokeRequired)
            {
                this.Invoke(action);
            }
            else
            {
                action();
            }



        }
        public enum DeployState
        {
            Run,
            Ok,
            Error
        }
        private void SetStatus(string status, Color color, DeployState state)
        {
            RunOnUiThread(() =>
            {
                lbStatus.ForeColor = color;
                lbStatus.Text = status;
                pictureBox2.Visible = true;
                switch (state)
                {
                    case DeployState.Run:
                        pictureBox2.Image = AndrysNet.HiUpdateTools_Addin.Resources.animatedCircle;
                        break;
                    case DeployState.Ok:
                        pictureBox2.Image = AndrysNet.HiUpdateTools_Addin.Resources.ic_check;
                        break;
                    case DeployState.Error:
                        pictureBox2.Image = AndrysNet.HiUpdateTools_Addin.Resources.ic_error;
                        break;
                }
            });
        }
        private bool ExistFolderOnFtp(FTPClient ftp, string path)
        {
            path = path.TrimEnd("/".ToCharArray());
            string folderName = path.Substring(path.LastIndexOf("/") + 1, path.Length - path.LastIndexOf("/") - 1);
            path = path.Substring(0, path.LastIndexOf("/")) + "/";

            string[] list = ftp.Dir(path);
            return list.Contains(folderName) || list.Contains(path + folderName);




        }
        private void CopyToFtp(FTPClient ftp, string sourceDir, string targetDir)
        {
            targetDir = targetDir.TrimEnd("/".ToCharArray()) + "/";

            if (!ExistFolderOnFtp(ftp, targetDir))
                ftp.MkDir(targetDir);
            foreach (var file in Directory.GetFiles(sourceDir))
            {
                if (file.IndexOf(".vshost") > -1 || file.IndexOf(".pdb") > -1)
                    continue;
                WriteLine("copy file '{0}'", file);


                ftp.Put(File.ReadAllBytes(file), targetDir + Path.GetFileName(file));
                // File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));
            }
            foreach (var directory in Directory.GetDirectories(sourceDir))
                CopyToFtp(ftp, directory, Path.Combine(targetDir, Path.GetFileName(directory)));
        }

        private bool CanotWriteVersion(string p)
        {
            foreach (ProjectConfig item in conf.Projects)
            {
                if (item.Name == p && !item.WriteVerion)
                    return true;
            }
            return false;

        }
        private void WriteLine(string txt, params object[] args)
        {
            WriteLine(string.Format(txt, args));

        }
        OutputWindowPane OutputPanel;
        private void WriteLine(string txt)
        {
            if (OutputPanel == null)
            {
               
                Window outputWindow;
                OutputWindow o;
                outputWindow = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput);
                o = (OutputWindow)(outputWindow.Object);
                foreach (OutputWindowPane owp in o.OutputWindowPanes)
                {
                    if (owp.Guid.ToUpper() == BUILD_OUTPUT_PANE_GUID)
                    {
                        OutputPanel = owp;
                        break;
                    }


                    //Window outputWindow = DTE.Windows.Item(vsWindowKindOutput);
                    //OutputWindow o = (OutputWindow)outputWindow.Object;
                    //OutputWindowPanes oo = o.OutputWindowPanes;
                }
                //OutputPanel = oo.Item("Build");
                if (OutputPanel != null)
                    OutputPanel.Activate();

            }
            OutputPanel.OutputString(string.Format("HiUpdateTools - {0} - ", DateTime.Now) + txt + Environment.NewLine);

        }
        void Copy(string sourceDir, string targetDir)
        {

            if (!Directory.Exists(targetDir))
                Directory.CreateDirectory(targetDir);
            foreach (var file in Directory.GetFiles(sourceDir))
            {
                if (file.IndexOf(".vshost") > -1 || file.IndexOf(".pdb") > -1)
                    continue;
                WriteLine("copy file '{0}'", file);

                Application.DoEvents();
                FileInfo fileInfo = new FileInfo(file);
                serverConfig.Files.Add(new ServerConfigFile() { Name = file.Replace(ProjectPath + "bin\\Release", ""), Date = fileInfo.LastWriteTimeUtc, Size = fileInfo.Length });
                using (ZipFile zipFile = new ZipFile())
                {
                    zipFile.AddFile(file, "");
                    zipFile.Save(Path.Combine(targetDir, Path.GetFileName(file) + ".deploy"));
                }

                // File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)), true);
            }
            foreach (var directory in Directory.GetDirectories(sourceDir))
            {
                if (directory.IndexOf("app.publish") > -1)
                    continue;
                Copy(directory, Path.Combine(targetDir, Path.GetFileName(directory)));
            }
        }
        string ProjectPath = "";
        public DeployConfig conf;
        private ClientConfig clientConfig;
        ProjectItem confFile;
        ProjectItem clientConfFile;
        public Project CurrentProject { get; set; }
        private const string vsProjectKindSolutionItems = "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}";
        //private const string vsWindowKindOutput = "{34E76E81-EE4A-11D0-AE2E-00A0C90FFFC3}";
        private const string BUILD_OUTPUT_PANE_GUID = "{1BD8A850-02D1-11D1-BEE7-00A0C913D1F8}";
        private ProjectItem _ChangeLogFile;
        private void DeployForm_Load(object sender, EventArgs e)
        {
            lbVersion.Text = string.Format(lbVersion.Text, this.GetType().Assembly.GetName().Version);
            int index = 1;
            tcWizard.SelectedIndex = 1;
            tcWizard.TabPages.OfType<TabPage>().ToList().ForEach(tab =>
            {

                Label label = new Label();
                label.Name = tab.Name;
                label.Tag = tab;
                label.Text = tab.Text;
                label.Click += (s, a) =>
                {



                    Label l2 = s as Label;
                    TabPage t = l2.Tag as TabPage;
                    tcWizard.SelectedTab = t;


                };
                label.Height = 25;
                label.Width = 182;
                label.Padding = new Padding(5, 0, 0, 0);
                label.Location = new Point(10, index * 30);
                label.TextAlign = ContentAlignment.MiddleLeft;
                ///  label.Location.Y = 30 * index;
                plMenu.Controls.Add(label);
                index++;


            });
            tcWizard.SelectedIndexChanged += tcWizard_SelectedIndexChanged;

            tcWizard.SelectedIndex = 0;

            cbApplicationType.DataSource = Enum.GetValues(typeof(ApplicationType));
            cbServerPathType.DataSource = Enum.GetValues(typeof(PathType));
            cbClientPathType.DataSource = Enum.GetValues(typeof(PathType));


            // CurrentProject = FindProject(projectName);

            ProjectPath = CurrentProject.FullName.Replace(CurrentProject.Name + new System.IO.FileInfo(CurrentProject.FullName).Extension, "");

            if (!System.IO.File.Exists(ProjectPath + "HiUpdate.xml"))
            {
                conf = new DeployConfig();
                conf.ApplicationName = CurrentProject.Name;
                conf.ServerPathType = PathType.file;
                Property assemblyVersion = CurrentProject.Properties.Item("AssemblyVersion");
                conf.Version = assemblyVersion.Value.ToString();
                conf.Save(ProjectPath + "HiUpdate.xml");
                // System.IO.File.WriteAllText(ProjectPath + "HiUpdate.xml", "xml");
                confFile = CurrentProject.ProjectItems.AddFromFile(ProjectPath + "HiUpdate.xml");
                CurrentProject.Save();
                var proj = (CurrentProject.Object as VSLangProj.VSProject);
                string folderPath = Path.GetDirectoryName(this.GetType().Assembly.Location) + "\\";

                if (CurrentProject.Kind == "{60DC8134-EBA5-43B8-BCC9-BB4BC16C2548}")
                {
                    proj.References.Add(folderPath + "HiUpdateTools.Client.Wpf.exe");
                }
                else
                {
                    proj.References.Add(folderPath + "HiUpdateTools.Client.Win.exe");

                }

            }
            else
            {
                confFile = CurrentProject.ProjectItems.Item("HiUpdate.xml");
                conf = DeployConfig.Load(ProjectPath + "HiUpdate.xml", typeof(DeployConfig)) as DeployConfig;

            }
            if (!System.IO.File.Exists(ProjectPath + "ChangeLog.txt"))
            {
                ///clientConfig = new ClientConfig();
                File.CreateText(ProjectPath + "ChangeLog.txt").Close();
             //   clientConfig.Save(ProjectPath + "ClientConfig.xml");
                // System.IO.File.WriteAllText(ProjectPath + "HiUpdate.xml", "xml");
                _ChangeLogFile = CurrentProject.ProjectItems.AddFromFile(ProjectPath + "ChangeLog.txt");
                _ChangeLogFile.Properties.Item("CopyToOutputDirectory").Value = 2;
                //clientConfFile.se
                CurrentProject.Save();
            
            
            }
            else
            {
                _ChangeLogFile = CurrentProject.ProjectItems.Item("ChangeLog.txt");
             

            }
            if (!System.IO.File.Exists(ProjectPath + "ClientConfig.xml"))
            {
                clientConfig = new ClientConfig();

                clientConfig.Save(ProjectPath + "ClientConfig.xml");
                // System.IO.File.WriteAllText(ProjectPath + "HiUpdate.xml", "xml");
                clientConfFile = CurrentProject.ProjectItems.AddFromFile(ProjectPath + "ClientConfig.xml");
                clientConfFile.Properties.Item("CopyToOutputDirectory").Value = 2;
                //clientConfFile.se
                CurrentProject.Save();

            }
            else
            {
                clientConfFile = CurrentProject.ProjectItems.Item("ClientConfig.xml");
                clientConfig = ClientConfig.Load(ProjectPath + "ClientConfig.xml", typeof(ClientConfig)) as ClientConfig;

            }
            if (conf.Projects == null)
                conf.Projects = new List<Core.ProjectConfig>();
            foreach (Project project in DTE.Solution.Projects)
            {
                if (project.Kind == vsProjectKindSolutionItems)
                {
                    //  return   project.ProjectItems.Item(projectName).ContainingProject;
                    foreach (ProjectItem subproject in project.ProjectItems)
                    {
                        if (subproject.SubProject != null)
                            AddProject(subproject.SubProject.UniqueName);
                    }
                }
                else
                {
                    AddProject(project.UniqueName);
                }


            }
            dgvProjects.DataSource = conf.Projects;
            dgvProjects.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            ///load server config

            txApplicationName.Text = conf.ApplicationName;
            txVersion.Text = conf.Version;
            cbApplicationType.SelectedItem = conf.DeployType;
            cbServerPathType.SelectedItem = conf.ServerPathType;
            txServerPath.Text = conf.ServerPath;
            txServerUserName.Text = conf.ServerUserName;
            txServerPassword.Text = conf.ServerPassword;
            chServerAnonymous.Checked = conf.ServerAnonymous;


            ///load client config
            txClientPath.Text = clientConfig.ClientPath;
            cbClientPassiveMode.Checked = clientConfig.PassiveMode;
            cbClientPathType.SelectedItem = clientConfig.ClientPathType;
            txClientUserName.Text = clientConfig.ClientUserName;
            try
            { //Convert.ToBase64String(Encoding.UTF8.GetBytes(txClientPassword.Text))
                if (!string.IsNullOrEmpty(clientConfig.ClientPassword))
                    txClientPassword.Text = Encoding.UTF8.GetString(Convert.FromBase64String(clientConfig.ClientPassword));
            }
            catch { }
            cbClientAnonymous.Checked = clientConfig.ClientAnonymous;
            cbClientAutoUpdate.Checked = clientConfig.AutoUpdate;

        }

        void tcWizard_SelectedIndexChanged(object sender, EventArgs e)
        {
            btNext.Enabled = tcWizard.SelectedIndex != tcWizard.TabCount - 1;
            btPrevious.Enabled = tcWizard.SelectedIndex != 0;

            plMenu.Controls.OfType<Label>().ToList().ForEach(l =>
            {
                if (l.Name != tcWizard.SelectedTab.Name)
                {
                    l.ForeColor = Color.Black;
                    l.Image = null;
                }
                else
                {
                    l.Image = AndrysNet.HiUpdateTools_Addin.Resources.WizardLabelImg;
                    l.ForeColor = Color.White;

                }

            });
            if (tcWizard.SelectedTab == tpChangeLog)
            {

                if (conf.ChangeLogs == null)
                {
                    conf.ChangeLogs = new List<VersionInfo>();
                }
                if (!string.IsNullOrEmpty(txVersion.Text))
                {
                    var info = conf.ChangeLogs.Find(item => item.Version == txVersion.Text);
                    if (info == null)
                    {
                        info = new VersionInfo() { Version = txVersion.Text, Date = DateTime.Now };
                        conf.ChangeLogs.Add(info);
                        cbVersionInfo.SelectedItem = info;

                    }
                    cbVersionInfo.DataSource = null;
                    cbVersionInfo.DataSource = conf.ChangeLogs;
                    cbVersionInfo.SelectedItem = info;
                    cbVersionInfo.Refresh();


                }


            }

        }

        private Project FindProject(string projectName)
        {
            foreach (Project project in DTE.Solution.Projects)
            {
                if (project.Kind == vsProjectKindSolutionItems)//.vsProjectKindSolutionItems)
                {
                    //  return   project.ProjectItems.Item(projectName).ContainingProject;
                    foreach (ProjectItem subproject in project.ProjectItems)
                    {
                        if (subproject.SubProject == null)
                            continue;
                        if (subproject.SubProject.UniqueName == projectName)
                            return subproject.SubProject;

                    }
                }
                if (project.UniqueName == projectName)
                    return project;



            }
            return null;
        }
        private void AddProject(string p)
        {
            bool exist = false;
            foreach (ProjectConfig item in conf.Projects)
            {
                if (item.Name == p)
                    exist = true;


            }
            if (!exist)
            {
                conf.Projects.Add(new ProjectConfig() { Name = p, WriteVerion = p == CurrentProject.UniqueName });
            }
        }
        private void chServerAnonymous_CheckedChanged(object sender, EventArgs e)
        {
            txServerUserName.Enabled = !chServerAnonymous.Checked;
            txServerPassword.Enabled = !chServerAnonymous.Checked;
        }



        private void btExportConfig_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog dialog = new SaveFileDialog())
            {
                dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*";
                // dialog.FilterIndex = 2 ;

                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    ClientConfig conf = new ClientConfig();
                    conf.ClientPath = txClientPath.Text;
                    conf.ClientPathType = (PathType)cbClientPathType.SelectedValue;
                    conf.ClientUserName = txClientUserName.Text;
                    conf.ClientPassword = Convert.ToBase64String(Encoding.UTF8.GetBytes(txClientPassword.Text));
                    conf.ClientAnonymous = cbClientAnonymous.Checked;
                    conf.AutoUpdate = cbClientAutoUpdate.Checked;
                    conf.Save(dialog.FileName);


                }



            }
        }


        private void btNext_Click(object sender, EventArgs e)
        {

            tcWizard.SelectedIndex++;


        }

        private void btPrevious_Click(object sender, EventArgs e)
        {

            tcWizard.SelectedIndex--;


        }

        private void DeployForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveConfig();
        }

        private void cbVersionInfo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbVersionInfo.SelectedItem != null)
            {
                rtbVersionInfo.Text = (cbVersionInfo.SelectedItem as VersionInfo).Info;


            }
        }

        private void rtbVersionInfo_TextChanged(object sender, EventArgs e)
        {
            if (cbVersionInfo.SelectedItem != null)
            {
                (cbVersionInfo.SelectedItem as VersionInfo).Info = rtbVersionInfo.Text;
            }
        }



        private void lbAboutInfo_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("https://hiupdatetools.codeplex.com/");
        }

        private void cbClientAnonymous_CheckedChanged(object sender, EventArgs e)
        {
            txClientPassword.Enabled = !cbClientAnonymous.Checked;
            txClientUserName.Enabled = !cbClientAnonymous.Checked;

        }


    }
}
